//
//  UserCenterViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVUser+SNS.h>
#import <UIImageView+WebCache.h>
#import <KVNProgress/KVNProgress.h>

#import "BSKUserCenterViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKUserInfoViewController.h"
#import "BSKLoginViewController.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "BSKAboutUsViewController.h"
#import "UIViewController+BSKToast.h"
#import "AFNetworking.h"
#import "BSKSyncManager.h"

@interface BSKUserCenterViewController () <UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIView *userInfoView;
@property (strong, nonatomic) UILabel *nickNameLabel;
@property (strong, nonatomic) UIImageView *headImageView;
@property (strong, nonatomic) UITableView *settingTableView;
@property (strong, nonatomic) UIButton *logoutButton;
@property (assign, nonatomic) NSInteger flag;
@property (strong, nonatomic) UISwitch *autoChoiceSwitch;
@property (strong, nonatomic) UISwitch *wifiChoiceSwitch;
@end

@implementation BSKUserCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.8148 green:0.8148 blue:0.8148 alpha:1.0];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userStatusDidChange:) name:BSKuserStatusChangeNotification object:nil];
    [self initializeUserInterface];
    [self initializeUIStatus];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _flag = 0;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if ([AVUser currentUser]) {
        [self submitCurrentStatus];
    }
    if (_flag == 1) {
        UINavigationController * navVC = self.navigationController;
        NSMutableArray * array =[NSMutableArray arrayWithArray:navVC.viewControllers];
        [array removeObject:self];
        navVC.viewControllers = array;
    }
}
- (void)initializeUserInterface {
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *coverView = [[UIVisualEffectView alloc]initWithEffect:efect];
    UIImageView *imageView = [[UIImageView alloc] init];
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.userInfoView = [[UIView alloc] init];
    UIView *placeHolderView = [[UIView alloc] init];
    self.nickNameLabel = [[UILabel alloc] init];
    self.headImageView = [[UIImageView alloc] init];
    self.settingTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.settingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.logoutButton = [[UIButton alloc] init];
    
    [self.view addSubview:imageView];
    [self.view addSubview:coverView];
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.userInfoView];
    [self.userInfoView addSubview:placeHolderView];
    [self.userInfoView addSubview:self.nickNameLabel];
    [self.userInfoView addSubview:self.headImageView];
    [self.view addSubview:self.settingTableView];
    [self.view addSubview:self.logoutButton];
    
    coverView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
    coverView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    
    imageView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    imageView.image = [BSKTheme curentTheme].themeImage;
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(StatusBarHeight + NavigationBarHeight);
    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"个人中心";
    [self.titleLabel sizeToFit];
    
    self.userInfoView.sd_layout.topSpaceToView(self.navView, 0)
    .leftEqualToView(self.navView)
    .rightEqualToView(self.navView)
    .heightIs(140);
    self.userInfoView.backgroundColor = [UIColor clearColor];
    
    placeHolderView.sd_layout.topEqualToView(self.userInfoView)
    .widthRatioToView(self.userInfoView, 1)
    .leftEqualToView(self.userInfoView)
    .heightIs(85);
    placeHolderView.backgroundColor = self.navView.backgroundColor;
    
    self.nickNameLabel.sd_layout.topSpaceToView(self.userInfoView, 10)
    .leftEqualToView(self.userInfoView)
    .widthRatioToView(self.userInfoView, 1)
    .heightIs(30);
    self.nickNameLabel.textAlignment = NSTextAlignmentCenter;
    self.nickNameLabel.textColor = [UIColor whiteColor];
    self.nickNameLabel.font = [UIFont systemFontOfSize:20];
    self.nickNameLabel.text = @"MicroMemory";
    
    self.headImageView.sd_layout.topSpaceToView(self.nickNameLabel, 5)
    .centerXIs(self.view.centerX)
    .widthIs(80)
    .heightIs(80);
    self.headImageView.image = [UIImage imageNamed:@"login-no"];
    self.headImageView.layer.cornerRadius = 40;
    self.headImageView.layer.masksToBounds = YES;
    
    self.settingTableView.sd_layout.topSpaceToView(self.userInfoView, 0)
    .widthRatioToView(self.view, 1)
    .leftEqualToView(self.userInfoView)
    .bottomSpaceToView(self.logoutButton, 15);
    self.settingTableView.backgroundColor = [UIColor clearColor];
    self.settingTableView.bounces = NO;
    self.settingTableView.showsVerticalScrollIndicator = NO;
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;
    
    self.logoutButton.sd_layout.bottomSpaceToView(self.view, 15)
    .leftSpaceToView(self.view, 30)
    .rightSpaceToView(self.view, 30)
    .heightIs(50);
    self.logoutButton.backgroundColor = [UIColor colorWithRed:0.7567 green:0.2153 blue:0.2928 alpha:1.0];
    self.logoutButton.layer.cornerRadius = 10;
    self.logoutButton.layer.masksToBounds = YES;
    [self.logoutButton setTitle:@"注销登录" forState:UIControlStateNormal];
    [self.logoutButton addTarget:self action:@selector(logoutButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)initializeUIStatus {
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser[@"nickName"]) {
        self.nickNameLabel.text = currentUser[@"nickName"];
    }
    if (currentUser[@"userHeader"]) {
        NSURL * url = [NSURL URLWithString:[currentUser objectForKey:@"userHeader"]];
        [self.headImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"login-no"]];
    }
    if (currentUser[@"autoChoice"]) {
        if ([currentUser[@"autoChoice"] isEqualToString:@"yes"]) {
            self.autoChoiceSwitch.on = YES;
            self.autoChoiceSwitch.selected = YES;
        }
    }
    if (currentUser[@"wifiChoice"]) {
        if ([currentUser[@"wifiChoice"] isEqualToString:@"yes"]) {
            self.wifiChoiceSwitch.on = YES;
            self.wifiChoiceSwitch.selected = YES;
        }
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@",object);
}
#pragma mark - 自定义方法
- (void)submitCurrentStatus {
    NSString *autoChoice = @"no";
    if (self.autoChoiceSwitch.selected) {
        autoChoice = @"yes";
    }
    NSString *wifiChoice = @"no";
    if (self.wifiChoiceSwitch.selected) {
        wifiChoice = @"yes";
    }
    [[AVUser currentUser] setObject:autoChoice forKey:@"autoChoice"];
    [[AVUser currentUser] setObject:wifiChoice forKey:@"wifiChoice"];
    [[AVUser currentUser] saveEventually];
}
- (void)presentAlertWithController:(UIViewController *)controller Message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
}
- (void)logoutButtonAction:(UIButton *)sender {
	[self submitCurrentStatus];
	NSString *autoChoice = @"no";
	if (self.autoChoiceSwitch.selected) {
		autoChoice = @"yes";
	}
	NSString *wifiChoice = @"no";
	if (self.wifiChoiceSwitch.selected) {
		wifiChoice = @"yes";
	}
	[[AVUser currentUser] setObject:autoChoice forKey:@"autoChoice"];
	[[AVUser currentUser] setObject:wifiChoice forKey:@"wifiChoice"];
	[KVNProgress show];
	[[AVUser currentUser] saveEventually:^(BOOL succeeded, NSError *error) {
		_flag = 1;
		[AVUser logOut];  //清除缓存用户对象
		[AVOSCloudSNS logout:AVOSCloudSNSQQ];
		[AVOSCloudSNS logout:AVOSCloudSNSSinaWeibo];
		[AVOSCloudSNS logout:AVOSCloudSNSWeiXin];
		[KVNProgress dismiss];
		if ([AVUser currentUser] == nil) {
			[[NSNotificationCenter defaultCenter] postNotificationName:BSKuserStatusChangeNotification object:nil];
			[self.navigationController MakeToast:@"用户已注销" WithTime:1.5];
		} else {
			[self MakeToast:@"注销登录失败，请重试" WithTime:1.5];
		}
		BSKLoginViewController *loginVC = [[BSKLoginViewController alloc] init];
		[self.navigationController pushViewController:loginVC animated:YES];
	}];
}
- (void)logout {
    // 注销登录事件
    [self submitCurrentStatus];
    NSString *autoChoice = @"no";
    if (self.autoChoiceSwitch.selected) {
        autoChoice = @"yes";
    }
    NSString *wifiChoice = @"no";
    if (self.wifiChoiceSwitch.selected) {
        wifiChoice = @"yes";
    }
    [[AVUser currentUser] setObject:autoChoice forKey:@"autoChoice"];
    [[AVUser currentUser] setObject:wifiChoice forKey:@"wifiChoice"];
    [[AVUser currentUser] saveEventually:^(BOOL succeeded, NSError *error) {
        _flag = 1;
        [AVUser logOut];  //清除缓存用户对象
        [AVOSCloudSNS logout:AVOSCloudSNSQQ];
        [AVOSCloudSNS logout:AVOSCloudSNSSinaWeibo];
        [AVOSCloudSNS logout:AVOSCloudSNSWeiXin];
        if ([AVUser currentUser] == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:BSKuserStatusChangeNotification object:nil];
            [self.navigationController MakeToast:@"用户已注销" WithTime:1.5];
        } else {
            [self MakeToast:@"注销登录失败，请重试" WithTime:1.5];
        }
    }];
}
- (void)autoSwitchAction:(UISwitch *)sender {
    sender.selected = !sender.selected;
}
- (void)wifiSwitchAction:(UISwitch *)sender {
    sender.selected = !sender.selected;
}
-(void)userStatusDidChange:(NSNotification *)notify{
    UIImage * head = notify.object;
    _headImageView.image = head;
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser[@"nickName"]) {
        self.nickNameLabel.text = currentUser[@"nickName"];
    }
}
#pragma mark - UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        return 3;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 25;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] init];
    UIView *lineView = [[UIView alloc] init];
    UILabel *titleLabel = [[UILabel alloc] init];
    [header addSubview:lineView];
    [header addSubview:titleLabel];
    lineView.sd_layout.topSpaceToView(header, 0)
    .leftSpaceToView(header, 30)
    .rightSpaceToView(header, 30)
    .heightIs(1);
    lineView.backgroundColor = [UIColor whiteColor];
    titleLabel.sd_layout.centerYIs(header.centerY + 1)
    .topSpaceToView(header, 10)
    .leftSpaceToView(header, 30)
    .rightSpaceToView(header, 30);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    switch (section) {
        case 0:
            titleLabel.text = @"用户信息设置";
            break;
        case 1:
            titleLabel.text = @"用户安全设置";
            break;
        case 2:
            titleLabel.text = @"同步设置";
            break;
        case 3:
            titleLabel.text = @"软件信息";
            break;
    }
    return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel *titleLabel = [[UILabel alloc] init];
    [cell addSubview:titleLabel];
    titleLabel.sd_layout.centerYIs(cell.centerY)
    .leftSpaceToView(cell, 70)
    .rightSpaceToView(cell, 70)
    .heightIs(30);
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.textColor = [UIColor whiteColor];
    if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0: {
                titleLabel.text = @"自动云端同步";
                self.autoChoiceSwitch = [[UISwitch alloc]init];
                [cell addSubview:self.autoChoiceSwitch];
                self.autoChoiceSwitch.sd_layout.centerYIs(cell.centerY)
                .rightSpaceToView(cell, 50);
                self.autoChoiceSwitch.backgroundColor = self.view.backgroundColor;
                self.autoChoiceSwitch.layer.cornerRadius = 15;
                self.autoChoiceSwitch.layer.masksToBounds = YES;
                [self.autoChoiceSwitch setTintColor:self.view.backgroundColor];
                [self.autoChoiceSwitch setThumbTintColor:[UIColor whiteColor]];
                [self.autoChoiceSwitch addTarget:self action:@selector(autoSwitchAction:) forControlEvents:UIControlEventValueChanged];
                break;
            }
            case 1: {
                titleLabel.text = @"仅在WIFI下同步";
                self.wifiChoiceSwitch = [[UISwitch alloc]init];
                [cell addSubview:self.wifiChoiceSwitch];
                self.wifiChoiceSwitch.sd_layout.centerYIs(cell.centerY)
                .rightSpaceToView(cell, 50);
                self.wifiChoiceSwitch.backgroundColor = self.view.backgroundColor;
                self.wifiChoiceSwitch.layer.cornerRadius = 15;
                self.wifiChoiceSwitch.layer.masksToBounds = YES;
                [self.wifiChoiceSwitch setTintColor:self.view.backgroundColor];
                [self.wifiChoiceSwitch setThumbTintColor:[UIColor whiteColor]];
                [self.wifiChoiceSwitch addTarget:self action:@selector(wifiSwitchAction:) forControlEvents:UIControlEventValueChanged];
                [self initializeUIStatus];
            }
                break;
            case 2: {
                titleLabel.text = @"立即同步";
                break;
            }
        }
    } else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (indexPath.section) {
            case 0:
                titleLabel.text = @"修改用户信息";
                break;
            case 1:
                cell.accessoryType = UITableViewCellAccessoryNone;
                titleLabel.text = @"修改登录密码";
                break;
            case 3:
                titleLabel.text = @"关于";
                break;
        }
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0: {
            BSKUserInfoViewController *userInfoVC = [[BSKUserInfoViewController alloc] init];
            [self.navigationController pushViewController:userInfoVC animated:YES];
            break;
        }
        case 1: {
            if ([AVUser currentUser].email) {
                UIAlertController *sendEmailAlert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认发送邮件以重置密码？" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [KVNProgress show];
                    [AVUser requestPasswordResetForEmailInBackground:[AVUser currentUser].email block:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            NSString *emailStr = [AVUser currentUser].email;
                            [self logout];
                            BSKLoginViewController *loginVC = [[BSKLoginViewController alloc] init];
                            [KVNProgress dismiss];
                            [self.navigationController pushViewController:loginVC animated:YES];
                            [self presentAlertWithController:loginVC Message:[NSString stringWithFormat:@"邮件已发送至%@，请更改密码后重新登录", emailStr]];
                        } else {
                            [KVNProgress dismiss];
                            NSString *emailStr = @"邮件发送失败，请检查网络连接！";
                            if (error.code == 1) {
                                emailStr = @"请不要往同一个邮件地址发送太多邮件！";
                            }
                            [self presentAlertWithController:self Message:emailStr];
                        }
                    }];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [sendEmailAlert addAction:sureAction];
                [sendEmailAlert addAction:cancleAction];
                [self presentViewController:sendEmailAlert animated:YES completion:nil];
            } else {
                [self presentAlertWithController:self Message:@"请注册后执行该操作"];
            }
            break;
        }
        case 2: {
			__weak typeof(self) weakSelf = self;
            if (indexPath.row == 2) {
                [self submitCurrentStatus];
				[[AVUser currentUser] refresh];
				AFNetworkReachabilityManager *rManger = [AFNetworkReachabilityManager sharedManager];
				[rManger startMonitoring];
				[rManger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
					if (status == 2) {
						[[BSKSyncManager shareSyncManager]startSyncWithController:weakSelf.navigationController];
					}else{
						UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前没有连接WiFi，真的要同步吗？" preferredStyle:UIAlertControllerStyleAlert];
						UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
							[[BSKSyncManager shareSyncManager]startSyncWithController:weakSelf.navigationController];
						}];
						UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
						[alert addAction:sureAction];
						[alert addAction:cancelAction];
						[weakSelf presentViewController:alert animated:YES completion:nil];
					}
				}];
            }
            break;
        }
        case 3: {
            BSKAboutUsViewController *userInfoVC = [[BSKAboutUsViewController alloc] init];
            [self.navigationController pushViewController:userInfoVC animated:YES];
            break;
        }
    }
}

@end
